﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using FirstFloor.ModernUI.Windows.Controls;
using Microsoft.Win32;
using Uinside.CreditSystem.DomainModels.Models;
using Uinside.CreditSystem.Services;
using Uinside.CreditSystem.WPF.Tools;
using Uinside.CreditSystem.WPF.Windows;
using Image = Uinside.CreditSystem.DomainModels.Models.Image;

namespace Uinside.CreditSystem.WPF.ViewModels
{
    public class CustomersWorkspaceVIewMode : ViewModelBase
    {
        public virtual bool IsCompany
        {
            get { return false; }
        }

        public override void Dispose()
        {
            if (_creditContext != null)
                _creditContext.Dispose();
            base.Dispose();
        }

        CreditContext _creditContext = new CreditContext();
        private CustomerService _customerService;
        public CustomerService CustomerService
        {
            get
            {
                if (_customerService == null)
                {
                    _customerService = new CustomerService(_creditContext);
                }
                return _customerService;
            }
        }

        private BanksService _banksServiceService;
        public BanksService BanksService
        {
            get
            {
                if (_banksServiceService == null)
                {
                    _banksServiceService = new BanksService(_creditContext);
                }
                return _banksServiceService;
            }
        }

        private PaymentTypeService _paymentTypeService;
        public PaymentTypeService PaymentTypeService
        {
            get
            {
                if (_paymentTypeService == null)
                {
                    _paymentTypeService = new PaymentTypeService(_creditContext);
                }
                return _paymentTypeService;
            }
        }

        private PaymentStatusService _paymentStatusService;
        public PaymentStatusService PaymentStatusService
        {
            get
            {
                if (_paymentStatusService == null)
                {
                    _paymentStatusService = new PaymentStatusService(_creditContext);
                }
                return _paymentStatusService;
            }
        }

        private BankAccountStatusService _bankAccountStatusService;
        public BankAccountStatusService BankAccountStatusService
        {
            get
            {
                if (_bankAccountStatusService == null)
                {
                    _bankAccountStatusService = new BankAccountStatusService(_creditContext);
                }
                return _bankAccountStatusService;
            }
        }

        private ObservableCollection<Customer> _customerCollection;
        public ObservableCollection<Customer> CustomerCollection
        {
            get
            {
                if (_customerCollection == null)
                {
                    RunBackgroundWorker((s, e) =>
                    {
                        SetBusyState(true);
                        _customerCollection = new ObservableCollection<Customer>(CustomerService.GetAll());
                    }, (s, e) =>
                    {
                        OnPropertyChanged("CustomerCollection");
                        SetBusyState(false);

                    });
                }
                return _customerCollection;
            }
        }


        private Customer _currentItem;
        public virtual Customer CurrentItem
        {
            get
            {
                return _currentItem;
            }
            set
            {
                _currentItem = value;
                OnPropertyChanged("CurrentItem");
            }
        }

        private RelayCommand<object> _saveCommand;
        public RelayCommand<object> SaveCommand
        {
            get
            {
                if (_saveCommand == null)
                    _saveCommand = new RelayCommand<object>(SaveAction, CanSave);
                return _saveCommand;
            }
        }

        private bool CanSave(object obj)
        {
            return true;
        }

        private void SaveAction(object obj)
        {
            SetBusyState(true);
            RunBackgroundWorker((s, e) =>
            {
                _creditContext.SaveChanges();
            }, (s, e) =>
            {
                SetBusyState(false);
                var dialog = new ModernDialog()
                {
                    Content = "保存成功",
                    Height = 50
                };
                dialog.ShowDialog();
            });
        }

        private RelayCommand<object> _deleteCommand;
        public RelayCommand<object> DeleteCommand
        {
            get
            {
                if (_deleteCommand == null)
                    _deleteCommand = new RelayCommand<object>(DeleteAction, CanDelete);
                return _deleteCommand;
            }
        }

        private bool CanDelete(object obj)
        {
            return true;
        }

        private void DeleteAction(object obj)
        {
            _creditContext.Customers.Remove(CurrentItem);
            _creditContext.SaveChanges();
            CustomerCollection.Remove(CurrentItem);
        }

        private RelayCommand<object> _addCommand;
        public RelayCommand<object> AddCommand
        {
            get
            {
                if (_addCommand == null)
                    _addCommand = new RelayCommand<object>(AddAction, CanAdd);
                return _addCommand;
            }
        }

        private bool CanAdd(object obj)
        {
            return true;
        }

        private void AddAction(object obj)
        {
            var customer = new Customer();
            this.CustomerCollection.Add(customer);
            this._creditContext.Customers.Add(customer);
            CurrentItem = customer;
        }



        private RelayCommand<object> _addBankAccountCommand;
        public RelayCommand<object> AddBankAccountCommand
        {
            get
            {
                if (_addBankAccountCommand == null)
                    _addBankAccountCommand = new RelayCommand<object>(AddBankAccountAction, CanAddBankAccount);
                return _addBankAccountCommand;
            }
        }

        private bool CanAddBankAccount(object obj)
        {
            return true;
        }

        private void AddBankAccountAction(object obj)
        {
            var bankAccount = new BankAccount() { BankId = BanksService.GetAll().First(i => i.Value == 1).Id, StatusId = BankAccountStatusService.GetAll().First(i => i.Value == 1).Id };
            if (CurrentItem.BankAccounts == null)
                CurrentItem.BankAccounts = new ObservableCollection<BankAccount>();
            CurrentItem.BankAccounts.Add(bankAccount);
        }

        private RelayCommand<BankAccount> _deleteBankAccountCommand;
        public RelayCommand<BankAccount> DeleteBankAccountCommand
        {
            get
            {
                if (_deleteBankAccountCommand == null)
                    _deleteBankAccountCommand = new RelayCommand<BankAccount>(DeleteBankAccountAction, CanDeleteBankAccount);
                return _deleteBankAccountCommand;
            }
        }

        private bool CanDeleteBankAccount(BankAccount obj)
        {
            return true;
        }

        private void DeleteBankAccountAction(BankAccount obj)
        {
            CurrentItem.BankAccounts.Remove(obj);
        }

        private RelayCommand<Customer> _refreshCommand;
        public RelayCommand<Customer> RefreshCommand
        {
            get
            {
                if (_refreshCommand == null)
                    _refreshCommand = new RelayCommand<Customer>(Refesh, CanRefesh);
                return _refreshCommand;
            }
        }

        private bool CanRefesh(Customer obj)
        {
            return true;
        }

        private void Refesh(Customer obj)
        {
            _creditContext.Entry(obj).Reload();
        }

        private RelayCommand<object> _uploadLogoCommand;
        public RelayCommand<object> UploadLogoCommand
        {
            get
            {
                if (_uploadLogoCommand == null)
                    _uploadLogoCommand = new RelayCommand<object>(UploadLogoAction, CanUploadLogo);
                return _uploadLogoCommand;
            }
        }

        private bool CanUploadLogo(object obj)
        {
            return true;
        }

        private void UploadLogoAction(object obj)
        {
            var FileDialog = new OpenFileDialog
            {
                Title = "选择图片",
                InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                Filter = "Image Files (*.gif,*.jpg,*.jpeg,*.bmp,*.png)|*.gif;*.jpg;*.jpeg;*.bmp;*.png",
                FilterIndex = 1
            };
            //CurrentItem.CompanyLogo
            if (FileDialog.ShowDialog() != true) return;
            SetBusyState(true);
            RunBackgroundWorker((s, e) =>
            {
                byte[] b = File.ReadAllBytes(FileDialog.FileName);
                if (CurrentItem.CompanyLogo == null)
                    CurrentItem.CompanyLogo = new Image();

                CurrentItem.CompanyLogo.Data = b;
                _creditContext.SaveChanges();
            }, (s, e) =>
            {
                SetBusyState(false);
            });
        }

        private RelayCommand<string> _entryCommand;
        public RelayCommand<string> EntryCommand
        {
            get
            {
                if (_entryCommand == null)
                    _entryCommand = new RelayCommand<string>(EntryAction, CanEntry);
                return _entryCommand;
            }
        }

        private bool CanEntry(string obj)
        {
            return true;
        }

        private void EntryAction(string obj)
        {
            var deposit = new DepositWindow();
            var viewModel = new DepositWindowViewModel();
            deposit.DataContext = viewModel;
            deposit.Buttons = new[] { deposit.OkButton, deposit.CloseButton };
            deposit.Title = obj;
            deposit.ShowDialog();

            if (deposit.DialogResult == null || deposit.DialogResult == false) return;
            SetBusyState(true);
            RunBackgroundWorker((s, e) =>
            {
                var entry = new Payment();
                entry.Type = obj == "入账" ? PaymentTypeService.GetAll().First(i => i.Value == 1) : PaymentTypeService.GetAll().First(i => i.Value == 2);
                entry.Borrower = CurrentItem;
                entry.Lender = CurrentItem;
                entry.ExpectDate = DateTime.Now;
                entry.PaymentDate = DateTime.Now;
                entry.RemindDate = DateTime.Now;
                entry.Status = PaymentStatusService.GetAll().First(i => i.Value == 2);
                entry.Sum = viewModel.Sum * (obj == "入账" ? 1 : -1);
                entry.Note = viewModel.Note;
                _creditContext.Payments.Add(entry);
                CurrentItem.Capital += entry.Sum;
                _creditContext.SaveChanges();
                e.Result = entry;
            }, (s, e) =>
            {
                CurrentItem.Deposits.Add(e.Result as Payment);
                SetBusyState(false);
            });
        }
    }
}
